package com.niubi.yygh.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niubi.yygh.common.exception.YyghException;
import com.niubi.yygh.enums.AuthStatusEnum;
import com.niubi.yygh.model.user.Patient;
import com.niubi.yygh.model.user.UserInfo;
import com.niubi.yygh.user.mapper.UserInfoMapper;
import com.niubi.yygh.user.service.PatientService;
import com.niubi.yygh.user.service.UserInfoService;
import com.niubi.yygh.vo.user.LoginVo;
import com.niubi.yygh.vo.user.UserAuthVo;
import com.niubi.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.JwtHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 牛俊杰
 * @since 2022-03-24
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
  @Autowired
  RedisTemplate<String,String> redisTemplate;

  @Autowired
  PatientService patientService;

  @Override
  public Map<String, Object> loginUser(LoginVo loginVo) {
    //获取手机号和验证码
    String phone = loginVo.getPhone();
    String code = loginVo.getCode();
    //非空判断
    if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
      throw new YyghException(20001,"登陆参数为空");
    }
    //验证码校验
    //从redis中根据手机号获取验证码
    String redsCode = redisTemplate.opsForValue().get(phone);
    //获取输入的验证码,比较输入的验证码和redis存储的是否一致
    if (!code.equals(redsCode)){
      throw new YyghException(20001,"验证码校验失败");
    }
    //########完善绑定手机号
    //获取openid
    String openid = loginVo.getOpenid();
    //判断openid是否为空
    if (StringUtils.isEmpty(openid)){//为空 则验证码登录
      //根据输入的手机号查询数据库,手机号是否第一次登录
      QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
      wrapper.eq("phone",phone);
      UserInfo userInfo = baseMapper.selectOne(wrapper);
      //如果手机号是第一次登录,把手机号信息添加数据库,完成注册
      if (userInfo==null){
        userInfo = new UserInfo();
        userInfo.setName("");
        userInfo.setPhone(phone);
        userInfo.setStatus(1);//用户状态正常
        baseMapper.insert(userInfo);
      }
      //判断用户是否被禁用
      if (userInfo.getStatus()==0){
        throw new YyghException(20001,"用户已经被禁用");
      }
      //如果不是第一次登录,直接返回需要数据
      Map<String,Object> map = this.get(userInfo);
      return map;
    }else {//如果不为空则绑定手机号
      QueryWrapper<UserInfo> wrapperPhone = new QueryWrapper<>();
      wrapperPhone.eq("phone",phone);
      UserInfo userInfoPhone = baseMapper.selectOne(wrapperPhone);

      if (userInfoPhone==null){
        UserInfo userInfoWx = this.selectUserByOpenId(openid);
        if (userInfoWx==null) {
          throw new YyghException(20001, "微信信息不存在");
        }
        userInfoWx.setPhone(phone);
        baseMapper.updateById(userInfoWx);
        Map<String,Object> map = this.get(userInfoWx);
        return map;
      }else {
        UserInfo userInfoWx = this.selectUserByOpenId(openid);
        userInfoWx.setPhone(userInfoPhone.getPhone());
        //用户真实姓名
        userInfoWx.setName(userInfoPhone.getName());
        userInfoWx.setCertificatesType(userInfoPhone.getCertificatesType());
        userInfoWx.setCertificatesNo(userInfoPhone.getCertificatesNo());
        userInfoWx.setCertificatesUrl(userInfoPhone.getCertificatesUrl());
        //删除手机号数据
        baseMapper.delete(new QueryWrapper<UserInfo>().eq("phone", phone));

        //更新
        baseMapper.updateById(userInfoWx);

        Map<String, Object> map = get(userInfoWx);
        return map;
      }
    }
  }
  private Map<String,Object> get(UserInfo userInfo) {
    //返回页面显示名称
    Map<String, Object> map = new HashMap<>();
    String name = userInfo.getName();
    if(StringUtils.isEmpty(name)) {
      name = userInfo.getNickName();
    }
    if(StringUtils.isEmpty(name)) {
      name = userInfo.getPhone();
    }
    map.put("name", name);
    //根据userid和name生成token字符串
    String token = JwtHelper.createToken(userInfo.getId(), name);
    map.put("token", token);
    return map;
  }

  @Override
  public UserInfo selectUserByOpenId(String openid) {
    QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
    wrapper.eq("openid",openid);
    UserInfo userInfo = baseMapper.selectOne(wrapper);
    return userInfo;
  }

  @Override
  public void userAuth(Long userId, UserAuthVo userAuthVo) {
    //根据Id查询数据
    UserInfo userInfo = baseMapper.selectById(userId);
    userInfo.setName(userAuthVo.getName());
    userInfo.setCertificatesType(userAuthVo.getCertificatesType());
    userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
    userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
    userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
    //进行信息更新
    baseMapper.updateById(userInfo);
  }

  @Override
  public IPage<UserInfo> selectPageUser(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
    //获取条件之
    String name = userInfoQueryVo.getKeyword();
    Integer authStatus = userInfoQueryVo.getAuthStatus();
    Integer status = userInfoQueryVo.getStatus();
    String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
    String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
    //判断条件是否为空,不为空,封装
    QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
    if (!StringUtils.isEmpty(name)){
      wrapper.like("name",name);
    }
    if (!StringUtils.isEmpty(status)){
      wrapper.eq("status",status);
    }
    if(!StringUtils.isEmpty(authStatus)) {
      wrapper.eq("auth_status",authStatus);
    }
    if(!StringUtils.isEmpty(createTimeBegin)) {
      wrapper.ge("create_time",createTimeBegin);
    }
    if(!StringUtils.isEmpty(createTimeEnd)) {
      wrapper.le("create_time",createTimeEnd);
    }
    //调用方法分页条件查询
    Page<UserInfo> pageModel = baseMapper.selectPage(pageParam, wrapper);
    pageModel.getRecords().stream().forEach(item->{
      this.packageUserInfo(item);
    });
    return pageModel;
  }

  @Override
  public void lock(Long userId, Integer status) {
    if (status==0 || status==1){
      UserInfo userInfo = this.getById(userId);
      userInfo.setStatus(status);
      this.updateById(userInfo);
    }
  }

  @Override
  public Map<String, Object> show(Long userId) {
    Map<String, Object> map = new HashMap<>();
    UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
    map.put("userInfo",userInfo);
    List<Patient> patientList = patientService.findAllUserId(userId);
    map.put("patientList",patientList);
    return map;
  }

  @Override
  public void approval(Long userId, Integer authStatus) {
    if (authStatus==2 || authStatus==-1){
      UserInfo userInfo = baseMapper.selectById(userId);
      userInfo.setAuthStatus(authStatus);
      baseMapper.updateById(userInfo);
    }
  }

  private UserInfo packageUserInfo(UserInfo userInfo) {
    //处理认证状态编码
    userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
    //处理用户状态 0  1
    String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
    userInfo.getParam().put("statusString",statusString);
    return userInfo;
  }
}
